package cn.gtv.sdk.dcas.api;

import android.content.Context;
import android.net.Uri;
import android.util.Log;

import com.sad.jetpack.v1.datamodel.api.IDataModelChainInput;
import com.sad.jetpack.v1.datamodel.api.IDataModelInterceptorInput;
import com.sad.jetpack.v1.datamodel.api.IDataModelRequest;
import com.sad.jetpack.v1.datamodel.api.utils.LogcatUtils;

import org.json.JSONArray;
import org.json.JSONObject;


public class SubmitTrackerListDataProtocolInputInterceptorV2 implements IDataModelInterceptorInput<String> {
    private Context context;
    private String serverToken;
    public SubmitTrackerListDataProtocolInputInterceptorV2(Context context, String serverToken) {
        this.context = context;
        this.serverToken=serverToken;
    }

    @Override
    public void onInterceptedInput(IDataModelChainInput<String> chainInput) throws Exception {
        IDataModelRequest request=chainInput.request();
        IDataModelRequest.Creator requestCreator=request.toCreator();
        String body=request.body();
        String url= request.url();
        requestCreator.addHeader("Authorization","DJ "+ serverToken);
        JSONArray jsonArray=new JSONArray(body);
        String path=Uri.parse(url).getPath();
        String ts=(System.currentTimeMillis()/1000)+"";
        String data=ts;
        String signature=SignatureV2Util.createSignatureV2(path,data,ts);
        //开始封装实际提交的json
        JSONObject newJson=CommonRequestData.createJson(ts,signature);
        newJson.put("eventData",jsonArray);
        LogcatUtils.e(true,"DCAS_UPLOADER","------------->埋点实际提交数据："+newJson.toString(4));
        //log("DCAS_UPLOADER","------------->埋点实际提交数据："+newJson.toString(4));
        requestCreator.body(newJson.toString());
        request=requestCreator.create();
        chainInput.proceed(request,null,chainInput.currIndex());
    }



    private void log(String tag,String xml){
        int max=1000;
        if(xml.length() > max) {
            for(int i=0;i<xml.length();i+=max){
                if(i+max<xml.length())
                    Log.e(tag+i,xml.substring(i, i+max));
                else
                    Log.e(tag+i,xml.substring(i, xml.length()));
            }
        } else
            Log.e(tag,xml);
    }


}
